package cn.xiongxf.service.impl;

import cn.xiongxf.domain.Movie;
import cn.xiongxf.domain.User;
import cn.xiongxf.domain.UserMovie;
import cn.xiongxf.feignclient.MovieFeignClient;
import cn.xiongxf.mapper.UserMapper;
import cn.xiongxf.service.UserService;
import cn.xiongxf.util.AjaxResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private MovieFeignClient movieFeignClient;

    @Override
    public List<Movie> findAll() {
        return movieFeignClient.findAll();
    }

    @Transactional
    @Override
    public AjaxResult purchase(UserMovie userMovie) {
        // 找到user对象
        User user = userMapper.loadByUserId(userMovie);
        if (user != null){
            // 调用movie服务,买票
            final AjaxResult ajaxResult = movieFeignClient.purchase(userMovie);  // 为啥自动有final？
            // 买票成功才扣余额
            if (ajaxResult.getSuccess().equals(true)){
                BigDecimal price = movieFeignClient.queryPrice(userMovie.getMovieId());
                final BigDecimal balance = user.getBalance().subtract(price);
                // 余额充足
                if (balance.compareTo(BigDecimal.ZERO)  > 0){
                    user.setBalance(balance);
                    user.setId(userMovie.getUserId());
                    // 更新user余额
                    userMapper.update(user);
                    return AjaxResult.me();
                }else {
                    return AjaxResult.me().setSuccess(false).setMessage("余额不足！");
                    // 分布式事务问题：余票和余额在不同服务，出现异常无法同步
                    // 余额不足可再调movie服务，把减过的余票再加一
                }
            }
        }
        return new AjaxResult(false,"该用户不存在!");
    }

    @Override
    public void add(User user) {
        userMapper.save(user);

        // 调用movie服务的送票接口
        movieFeignClient.presented(user.getId());
    }

    @Override
    public AjaxResult watch(UserMovie userMovie) {
        return movieFeignClient.watch(userMovie);
    }


}
